<?php
/**
 * Created by PhpStorm.
 * User: 1
 * Date: 2017-03-17
 * Time: 15:38
 */

namespace app\src\sunsun\server\action;

use app\src\base\helper\ResultHelper;
use app\src\base\helper\ValidateHelper;
use app\src\base\logic\BaseLogic;
use app\src\sunsun\common\helper\SunsunEncodeHelper;
use GatewayClient\Gateway;
use think\Exception;


require_once __DIR__ . '/../../../../../vendor/autoload.php';

//设置register服务地址
//SServer register服务 端口 1212
Gateway::$registerAddress = "101.37.37.167:1212";

class SServerBaseAction
{

    public function sendReqToClient($did, $data, BaseLogic $logic)
    {
        if (empty($data)) {
            return ResultHelper::error('不能发送空数据');
        }
        $ret = SunsunEncodeHelper::encode($did, $data, $logic);
        if ($ret['status']) {
            $result = $logic->getInfo(['did' => $did]);
            if (ValidateHelper::legalArrayResult($result)) {
                $tcp_client_id = $result['info']['tcp_client_id'];
                $ret = $this->sendToClient($did, $ret['info'], $tcp_client_id);
            }
        }
        return $ret;
    }

    protected function sendToClient($did, $msg, $tcp_client_id = '')
    {
        if (empty($msg)) {
            return ResultHelper::error('不能发送空数据');
        }
        try {
            if (!empty($tcp_client_id)) {
                Gateway::sendToClient($tcp_client_id, $msg);
            } else {
                Gateway::sendToUid($did, $msg);
            }

        } catch (Exception $ex) {
            return ResultHelper::error(lang('tcp_service_exception') . $ex->getMessage());
        }
        return ResultHelper::success(lang('device_cmd_send_success'));
    }
}